/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.mqtt.mqttv3

import cool.taomu.mqtt.mqttv3.Topic.MessageType
import cool.taomu.utils.crypto.Base64
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.Logger
import org.slf4j.LoggerFactory

@Accessors
abstract class MqttCallback extends MqttCallbackExtend implements org.eclipse.paho.client.mqttv3.MqttCallback {
	final static Logger LOG = LoggerFactory.getLogger(MqttCallback);
	MqttClient client;
	MqttConnectOptions options;
	String host;
	int port;
	String password;
	String username;

	def void setClient(MqttClient client) {
		this.client = client;
	}

	def void setOptions(MqttConnectOptions options) {
		this.options = options;
	}

	override connectionLost(Throwable cause) {
		LOG.debug("连接丢失", cause);
		//reconnect(this.client,this.options);
	}

	override deliveryComplete(IMqttDeliveryToken token) {
		token.topics.forEach[
			LOG.debug("Client deliveryComplete : {}", it)
		]
	}

	override messageArrived(String topic, MqttMessage message) throws Exception {
		var byte[] base64 = new Base64(message.getPayload()).decode();
		val byte[] payload = this.message(topic,base64);
		if(payload !== null) {
			var topics = this.getClass().getAnnotation(Topics);
			topics.value.filter[it.messageType == MessageType.SENDER].filterNull.forEach[
				MqttV3Service.sender(it,host,port,username,password,payload);
			]
		}
	}

	abstract def byte[] message(String topic,byte[] message);
}
